package com.grgbanking.it.project.controller;


import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.grgbanking.it.common.Constant;
import com.grgbanking.it.common.json.JSONHelper;
import com.grgbanking.it.project.component.WXProjectConstant;
import com.grgbanking.it.project.entity.OperationWork;
import com.grgbanking.it.project.entity.OperationWorkHandle;
import com.grgbanking.it.project.service.IOperationWorkService;
import com.grgbanking.it.system.entity.GrgemEquipments;
import com.grgbanking.it.system.entity.User;
import com.grgbanking.it.system.service.IOaService;
import com.grgbanking.it.system.service.IUserService;
import com.grgbanking.it.wx.common.WXConstant;
import com.grgbanking.it.wx.entity.WXPassiveMessage;
import com.grgbanking.it.wx.entity.WXVerify;

/**
 * 微信运维工作入口
 * WXController
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2014-11-4 下午1:21:40
 * 
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/wx/operationWork")
public class WXOperationWorkController {
	private Integer agentId = WXProjectConstant.REPAIR_AGENT_ID;
	@Autowired
	private IOperationWorkService operationWorkService;
	@Autowired
	private IOaService oaService;
	@Autowired
	private IUserService userService;
	
	/**
	 * 回调接口校验
	 * apiWhenGet
	 * 
	 * @param verify
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody  
	@RequestMapping(value="api",method=RequestMethod.GET)
	public String apiWhenGet(WXVerify verify){  
		String echo = "error";
		try {
			echo =  operationWorkService.getEcho(verify);
		} catch (Exception e) {
			e.printStackTrace();
		}  
		
		return echo;
	}   
	
	/**
	 * 信息接收入口
	 * apiWhenPost
	 * 
	 * @param request
	 * @param verify
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="api", method = RequestMethod.POST)  
    public void apiWhenPost(HttpServletRequest request,HttpServletResponse response,WXVerify verify){ 
		try {
			String backMsg = null;
			
			//从请求中读取整个post数据  
			InputStream inputStream = request.getInputStream();  
	        String postData = IOUtils.toString(inputStream, "UTF-8");  
	        verify.setPostData(postData);
	       
	        WXPassiveMessage recivedMessage = operationWorkService.reciveMsg(verify);
	        if(recivedMessage.getAgentID() == agentId){
	        	//来自IT服务支持模块的信息
	        	if(recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_IMAGE)){
	        		//图片报修
	        		OperationWork work = new OperationWork();
		        	work.setUsername(recivedMessage.getFromUserName());
		        	work.setWorkOrigin("微信");
		        	work.setPicUrl(recivedMessage.getPicUrl());
		        	work.setMsgType(0);
		        	operationWorkService.saveOrUpdate(work);
		        	
		        	//回复加密信息
		        	backMsg = operationWorkService.getMessageWhenRecived(recivedMessage.getFromUserName(),verify, 1);
	        	}else if(recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_TEXT)){
	        		if(NumberUtils.isNumber(recivedMessage.getContent())){
	        			//如果回复的是数字则为评价
	        			OperationWork work = operationWorkService.updateWhenFeedback(recivedMessage.getFromUserName(), Integer.valueOf(recivedMessage.getContent()));
	        			
	        			if(work == null){
	        				//回复评价失败信息
	        				backMsg = operationWorkService.getMessageWhenRecived(recivedMessage.getFromUserName(),verify, 3);
	        			}else{
	        				//回复评价成功信息
	        				backMsg = operationWorkService.getMessageWhenRecived(recivedMessage.getFromUserName(),verify, 2);
	        			}
	        		}
	        	}
	        	
	        }
	        if(backMsg != null){
	        	response.setCharacterEncoding("UTF-8");
	 	        response.getWriter().print(backMsg);
	        }
	       
		} catch (Exception e) {
			e.printStackTrace();
		}  

    }  
	
	
	/**
	 * 微信菜单入口(除扫一扫外)
	 * 
	 * repair
	 * 
	 * @param code
	 * @param state
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("{type}")
	public ModelAndView menu(@PathVariable("type") String type,HttpServletRequest request, String code,Integer state){
		ModelAndView view = new ModelAndView();
		try {
			User user = userService.getUserByCode(code,agentId);
			if(user == null){
				view.setViewName("redirect:/wx/error.jsp");
			}else{
				request.setAttribute("user", user);
				
				if(type.equals("progress") || type.equals("history")){
					//进度 //报修历史
					int t = 1; //查询中使用到的类型
					String title = "报修进度";
					if(type.equals("history")){
						t = 2;
						title = "报修历史";
					}
					request.setAttribute("title", title);
					request.setAttribute("type", t);

					view.setViewName("/wx/operation/progress.jsp");
				}else if(type.equals("engineer")){
					if(user.getAuthority().isCommon(Constant.MODULE_OPERATION_WORK)){
						//没有执行权限
						view.setViewName("redirect:/wx/authority.jsp");
					}else{
						//我的工作  (工程师)
						request.setAttribute("state", state);
						view.setViewName("/wx/operation/engineer.jsp");
					}
					
				} 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return view; 
	}
	

	/**
	 * 报修功能(扫一扫及描述保修)
	 * 
	 * repair
	 * 
	 * @param device
	 * @param request
	 * @param code
	 * @param state
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("repair/{device}")
	public ModelAndView repair(@PathVariable("device") String device,HttpServletRequest request, String code,Integer state){
		ModelAndView view = new ModelAndView();
		try {
			User user = userService.getUserByCode(code,agentId);
			request.setAttribute("user", user);
			if(user == null){
				view.setViewName("redirect:/wx/error.jsp");
			}else{
				//报修
				if(!device.equals("nodevice")){
					GrgemEquipments equipment = oaService.getEquipmentById(device);
					User equipmentKeeper = userService.getUserByUsername(equipment.getUseUser());
					request.setAttribute("equipment", equipment);
					request.setAttribute("keeper", equipmentKeeper);
				}
				
				view.setViewName("/wx/operation/repair.jsp");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return view;
	}
	
	@ResponseBody  
	@RequestMapping(value="search/{state}/{userId}",method=RequestMethod.GET)
	public Object searchSupplierMsn(@PathVariable("state")Integer state,@PathVariable("userId")String userId,Integer type,Integer page,Integer pageSize){  
		String json = null;
		try {
			User user = userService.getUserByUsername(userId);
			json = operationWorkService.findWhenLoad(user,page,pageSize, state, type);
		} catch (Exception e) {
			e.printStackTrace();
			json = JSONHelper.getExceptionMessage(e);
		}  
		return json;  
	}
	
	/**
	 * 从微信过来新的工作
	 * @param operationWork
	 * @return
	 */
	@RequestMapping(value="new/{username}",method=RequestMethod.POST)
	public ModelAndView newFormWX(@PathVariable("username") String username,OperationWork operationWork){  
		ModelAndView view = new ModelAndView();
		try {
			operationWork.setWorkOrigin("微信");
			operationWork.setUsername(username);
			operationWork.setMsgType(3);
			operationWorkService.saveOrUpdate(operationWork);
			view.setViewName("redirect:/wx/success.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return view;  
	}   

	/**
	 * 微信上分配工作
	 * distribute
	 * 
	 * @param workId
	 * @param engineers
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("distribute/{workId}")
	public ModelAndView distribute(@PathVariable("workId") Integer workId,String[] engineers){  
		ModelAndView view = new ModelAndView();
		try {
			operationWorkService.updateForDistribute(workId, engineers);
			view.setViewName("redirect:/wx/success.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return view;  
	}   
	
	/**
	 * 微信上处理工作
	 * handle
	 * 
	 * @param workId
	 * @param engineer
	 * @param describe
	 * @param operationWorkHandle
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("handle/{workId}")
	public ModelAndView handle(@PathVariable("workId") Integer workId,String engineer,String describe,OperationWorkHandle operationWorkHandle){  
		ModelAndView view = new ModelAndView();
		try {
			User handler = userService.getUserByUsername(engineer);
			operationWorkService.updateForHandle(workId, describe, operationWorkHandle, handler);
			view.setViewName("redirect:/wx/success.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return view;  
	}  
	
	  
	
	/**
	 * 工作分配及处理页面
	 * work
	 * 
	 * @param id
	 * @param username
	 * @param request
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("{type}/{username}/{id}")
	public ModelAndView work(@PathVariable("type") String type,@PathVariable("username") String username,@PathVariable("id") Integer id,HttpServletRequest request){
		ModelAndView view = new ModelAndView();
		try {
			User user = userService.getUserByUsername(username);
			
			if (user == null) {
				view.setViewName("redirect:/wx/error.jsp");
			}else{
				
				OperationWork work = operationWorkService.findWorkById(id);
				List<User> engineers = userService.findEngineers();
				User equipmentKeeper = null;
				if(work.getEquipment() != null){
					equipmentKeeper = userService.getUserByUsername(work.getEquipment().getUseUser());
				}
				
				request.setAttribute("keeper", equipmentKeeper);
				
				request.setAttribute("user", user);
				request.setAttribute("work", work);
				request.setAttribute("engineers", engineers);
				
				if (type.equals("distribute")) {
					//分配工作
					view.setViewName("/wx/operation/distribute.jsp");
				} else if (type.equals("handle")) {
					//处理工作
					view.setViewName("/wx/operation/handle.jsp");
				} else if (type.equals("lookHandle")) {
					//查看工作处理明细
					List<OperationWorkHandle> handles = operationWorkService.findWorkHandles(id);
					request.setAttribute("handles", handles);
					view.setViewName("/wx/operation/handle_detail.jsp");
				} else if (type.equals("cancle")) {
					//取消工作
					operationWorkService.delete(user, id);
					view.setViewName("redirect:/wx/success.jsp");
				} 
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}	
	
	
	
}
